package org.whale.dao;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.mongodb.client.result.UpdateResult;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;
import org.whale.entity.ChatMessages;

import java.util.List;

/**
 * 对话记录持久化
 */
@Repository
@Slf4j
public class ChatMessageRepository implements ChatMemoryStore {

    @Resource
    private MongoTemplate mongoTemplate;


    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        Query query = new Query(Criteria.where("messageId").is(memoryId));
        ChatMessages chatMessages = mongoTemplate.findOne(query, ChatMessages.class);
        log.debug("持久化 - 查询对话消息 memoryId = {}",memoryId);
        if(ObjectUtil.isNull(chatMessages)){
            return CollectionUtil.newArrayList();
        }

        List<ChatMessage> chatMessageList = ChatMessageDeserializer.messagesFromJson(chatMessages.getContent());

        return chatMessageList;

    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> messages) {
        log.debug("持久化 - 插入或更新消息 messages = {}",messages);

        Query query = new Query(Criteria.where("messageId").is(memoryId));

        Update update = new Update();
        update.set("content", ChatMessageSerializer.messagesToJson(messages));
        mongoTemplate.upsert(query, update, ChatMessages.class);
    }

    @Override
    public void deleteMessages(Object memoryId) {
        log.debug("持久化 - 删除对话消息 memoryId = {}",memoryId);
        mongoTemplate.remove(memoryId);
    }
}